package agent

import (
	"io/ioutil"
	"net/http"
	"net/url"
	"strings"
	"time"

	"go.uber.org/zap"
)

type server struct {
	key      string
	addr     string
	isreport bool
}

func newserver() *server {
	return &server{}
}

func (s *server) start() error {
	go func() {
		for {
			time.Sleep(10 * time.Second)
			if s.isreport {
				if err := s.report(); err != nil {
					Logger.Warn("report", zap.Error(err))
				}
			}
		}
	}()
	return nil
}

func (s *server) isequal(key, addr string) bool {
	if !strings.EqualFold(key, s.key) {
		return false
	}

	if !strings.EqualFold(addr, s.addr) {
		return false
	}
	return true
}

func (s *server) update(key, addr string) {
	s.addr = addr
	s.key = key
	s.isreport = true
}

func (s *server) stop() {
	s.addr = ""
	s.key = ""
	s.isreport = false
}

func (s *server) report() error {
	resp, err := http.PostForm("http://"+s.addr, url.Values{"name": {gAgent.Name}, "host": {"1.1.1.1"}})
	if err != nil {
		return err
	}

	defer resp.Body.Close()

	_, err = ioutil.ReadAll(resp.Body)

	if err != nil {
		return err
	}

	return nil
}
